<script setup lang="ts">
import "@wangeditor/editor/dist/css/style.css";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";

import { onBeforeUnmount, ref, shallowRef } from "vue";
import ReCol from "@/components/ReCol";
import { scriptFormRules } from "./utils/rule";
import { FormProps } from "./utils/types";

// 编辑器相关
const mode = "default";
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

const toolbarConfig: any = { excludeKeys: ["fullScreen", "group-image", "group-video"] };
const editorConfig = { placeholder: "请输入内容..." };

const handleCreated = editor => {
  // 记录 editor 实例，重要！
  editorRef.value = editor;
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({
    catalogueOption: [],
    id: "",
    title: "",
    content: "",
    cateId: ""
  })
});

const ruleFormRef = ref();
const newFormInline = ref(props.formInline);

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef });
</script>

<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="scriptFormRules"
    label-width="80px"
  >
    <el-row :gutter="30">
      <re-col :value="24" :xs="24" :sm="24">
        <el-form-item label="标题:" prop="title">
          <el-input
            v-model="newFormInline.title"
            clearable
            maxlength="50"
            placeholder="请输入"
            show-word-limit
          />
        </el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
        <el-form-item label="所属目录" prop="cateId">
          <el-select
            v-model="newFormInline.cateId"
            placeholder="请选择"
            class="w-full"
            clearable
          >
            <el-option
              v-for="(item, index) in newFormInline.catalogueOption"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </re-col>
      <re-col :value="24" :xs="24" :sm="24">
        <el-form-item label="内容" prop="content">
          <el-card shadow="never">
            <div class="wangeditor" >
              <Toolbar
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
                style="border-bottom: 1px solid #ccc"
              />
              <Editor
                v-model="newFormInline.content"
                :defaultConfig="editorConfig"
                :mode="mode"
                style="height: 400px; overflow-y: hidden"
                @onCreated="handleCreated"
              />
            </div>
          </el-card>
        </el-form-item>
      </re-col>
    </el-row>
  </el-form>
</template>

<style scoped lang="scss">
:deep(.el-card__body){
  padding: 0;
}
</style>
